#include <iostream>
#include <cstdio>
#include <vector>
#include "UdpServer.hpp"
#include "Comm.hpp"

void Usage(const std::string& proc)
{
    // std::cout << "Usage: \n\t" << proc << " udpserver_ip udpserver_port" << std::endl;
    std::cout << "Usage: \n\t" << proc << " udpserver_port" << std::endl;
}

std::vector<std::string> black_words = {
    "rm",
    "unlink",
    "cp",
    "mv",
    "chmod",
    "exit",
    "reboot",
    "halt",
    "shutdown",
    "top",
    "kill",
    "dd",
    "vim",
    "vi",
    "nano",
    "man"
};

bool SafeCheck(std::string command)
{
    for(auto &k : black_words)
    {
        std::size_t pos = command.find(k);
        if(pos != std::string::npos) return false;
    }

    return true;
}

std::string OnMessageDefault(std::string request)
{
    return request + ":[haha got you!!!]";
}

std::string ExcuteCommand(std::string command)
{
    (!SafeCheck(command)) return "bad gay!!";
    std::cout << "get a message: " << command << std::endl;
    FILE* fp = popen(command.c_str(), "r");
    if(fp == nullptr)
    {
        return "execute error, reason is unknown";
    }

    char buffer[1024];
    std::string response;
    while(true)
    {
        char *s = fgets(buffer, sizeof(buffer), fp);
        if(!s) break;
        else response += buffer;
    }
    pclose(fp);
    return response.empty() ? "success" : response;
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(Usage_Err);
    }
    UdpServer udpserver(ExcuteCommand, std::stoi(argv[1]));
    udpserver.Init();
    udpserver.Start();
    return 0;
}